<template>
  <view class="container">
    <mescroll-body ref="mescrollRef" :sticky="true" @init="mescrollInit" :down="{ native: true }" @down="downCallback" :up="upOption"
      @up="upCallback">
	  <view class="live-bg">
	  	<view class="live-list">
			<view class="live-item-" v-for="(item,index) in courseLists" :key="item.id" @click="goLive(item)">
				<!-- <image class="live-image" src="/static/img/live_img2.jpg" mode="widthFix"></image> -->
				<image class="live-image" :src="getImgUrl(item.thumbnail)" mode="aspectFill"></image>
				<!-- <view class="live-tag">
					<u-tag :text="item.permission == 10 ? '所有人' : item.permission == 20 ? '会员' : '-'" mode="light" type="success" size="mini" />
				</view> -->
				<view class="live-title">{{item.title}}</view>
				<view class="live-teacher-name">{{item.teacher}}</view>
				<!-- <view class="expire_time" v-if="get_expire_time(item.expire_time) > 0"><u-count-down :timestamp="get_expire_time(item.expire_time)"></u-count-down></view> -->
				<view class="expire_time" v-if="item.isShowAirtime && item.expire_time > 0">
				    <u-icon name="lock" color="#12a15c" size="40" style="margin-bottom: 10rpx;margin-top: 12rpx;"></u-icon>
				    <u-count-down separator-size="26" color="#12a15c" :height="30" :timestamp="item.expire_time" @end="handleEnd(index,item)"></u-count-down>
				</view>
			</view>
	  	</view>
	  </view>
   </mescroll-body>
  </view>
</template>

<script>
  import SettingKeyEnum from '@/common/enum/setting/Key'
  import SettingModel from '@/common/model/Setting'
  import * as CategoryApi from '@/api/category'
  import Search from '@/components/search'
  import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins'
  import { timestampChangDate, ImgUrlPrefix } from '@/utils/util.js'
  import { getEmptyPaginateObj, getMoreListData } from '@/core/app'
  import * as FindApi from '@/api/find'
  // 最后一次刷新时间
  let lastRefreshTime;
  // 每页记录数量
  const pageSize = 15
  export default {
    mixins: [MescrollMixin],
    components: {
      Search,
    },
    data() {
      return {
        // 正在加载中
        isLoading: true,
		// 上拉加载配置
		upOption: {
		  // 首次自动执行
		  auto: true,
		  // 每页数据的数量; 默认10
		  page: { size: pageSize },
		  // 数量要大于4条才显示无更多数据
		  noMoreSize: 4,
		  // 空布局
		  empty: {
		    tip: '亲，暂无课程记录'
		  }
		},
		// 课程列表数据
		list: {
			data: []
		},
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
      // 加载页面数据
      this.onRefreshPage()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      // 每间隔5分钟自动刷新一次页面数据
      const curTime = new Date().getTime()
      if ((curTime - lastRefreshTime) > 5 * 60 * 1000) {
        this.onRefreshPage()
      }
    },
	computed:{
		courseLists() {
		  return this.list.data.map(item => {
			   return { ...item, expire_time: item.expire_time ? this.get_expire_time(item.expire_time) : -1, isShowAirtime: true }
		  })
		} 
	},
    methods: {
	  // 转换时间戳
	  formatTime (data) {
	  	const currTime = timestampChangDate('YYYY-mm-dd', data * 1000)
		return currTime
	  },
      // 刷新页面
      onRefreshPage() {
        // 记录刷新时间
        lastRefreshTime = new Date().getTime()
        // 获取页面数据
        // this.getPageData()
      },

      // 获取页面数据
      getPageData() {
        const app = this
        app.isLoading = true
        Promise.all([
            // 获取分类模板设置
            // 优化建议: 可以将此处的false改为true 启用缓存
            SettingModel.data(false),
            // 获取分类列表
            CategoryApi.list()
          ])
          .then(result => {
            // 初始化分类模板设置
            app.initSetting(result[0])
            // 初始化分类列表数据
            app.initCategory(result[1])
          })
          .finally(() => app.isLoading = false)
      },
	  
       /**
       * 上拉加载的回调 (页面初始化时也会执行一次)
       * 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10
       * @param {Object} page
       */
      upCallback(page) {
	    console.log(page)
        const app = this
        // 设置列表数据
        app.getLiveList(page.num)
          .then(list => {
            const curPageLen = list.items.length
            const totalSize = list.total
            app.mescroll.endBySize(curPageLen, totalSize)
          })
          .catch(() => app.mescroll.endErr())
      },
	  
	  // 课程列表
	  getLiveList(pageNo =1) {
		const app = this
		return new Promise((resolve, reject) => {
		 FindApi.courseList({ page: pageNo }, { load: false })
		    .then(result => {
		      // 合并新数据
		      const newList = result.data
		      app.list.data = getMoreListData(newList, app.list, pageNo)
		      resolve(newList)
		    })
		})
	  },
      /**
       * 初始化分类模板设置
       * @param {Object} result
       */
      initSetting(setting) {
        this.setting = setting[SettingKeyEnum.PAGE_CATEGORY_TEMPLATE.value]
      },

      /**
       * 初始化分类列表数据
       * @param {Object} result
       */
      initCategory(result) {
        this.list = result.data.list
      },
       // 跳转详情页
	   goLive(val) {
		   const app = this
		   if(val.expire_time <= 0){
			   this.$navTo('pages/course/course', { id: val.id, name: val.title, thumbnail: val.thumbnail })
		   } else {
			    app.$toast('锁定时间无法进入')
		   }
	   },
	   // 倒计时结束事件
	   handleEnd(index, val) {
		  console.log('倒计时结束')
		  this.list.data[index].isShowAirtime = false
	   },
	   // 图片地址拼接
	   getImgUrl(val) {
	       const url = ImgUrlPrefix(val)
	       return url
	   },
	   
	   get_expire_time: function(val) {
		    const date = new Date().getTime();
			if(val) {
				let time = val * 1000 - date
				console.log(date,time)
				return time
			} else {
				return ''
			}
	   }
    },

    /**
     * 设置分享内容
     */
    onShareAppMessage() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/live/index?' + app.$getShareUrlParams()
      }
    },

    /**
     * 分享到朋友圈
     * 本接口为 Beta 版本，暂只在 Android 平台支持，详见分享到朋友圈 (Beta)
     * https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
     */
    onShareTimeline() {
      const app = this
      return {
        title: _this.templet.shareTitle,
        path: '/pages/live/index?' + app.$getShareUrlParams()
      }
    }

  }
</script>

<style>
  page {
    background: #fff;
  }
</style>
<style lang="scss" scoped>
  .live-bg{
  	  background-color: #f3f7f8;
  	  // padding: 16rpx 0;
  	  .live-list{
  	  	  display: flex;
  	  	  flex-wrap: wrap;
  	  	  justify-content: space-between;
  	  	  padding: 30rpx 40rpx;
  		  background-color: #fff;
  	  	  .live-item-{
  	  		  max-width: 48%;
  	  		  flex: 0 0 50%;
  	  		  color: #666;
  	  		  line-height: 54rpx;
			  box-shadow: 0 1rpx 8rpx rgba(0, 0, 0, 0.1);
			  border-radius: 16rpx;
			  margin-bottom: 40rpx;
			  position: relative;
  	  		  .live-image{
  	  			  width: 100%;
				  max-height: 176rpx;
				  border-top-right-radius: 16rpx;
				  border-top-left-radius: 16rpx;
				  background-color: #eef0f5;
  	  		  }
			  .live-tag{
				  position: absolute;
				  top: 6rpx;
				  left:16rpx;
			  }
  	  		  .live-title{
  	  			  color: #12a15c;
  	  			  padding: 0 20rpx;
  	  		  }
			  .live-teacher-name{
				   padding: 0 20rpx;
			  }
  	  		  .expire_time{
  	  			  position: absolute;
				  top: 0;
				  width: 100%;
				  height: 71%;
				  text-align: center;
				  padding-top: 18rpx;
				  border-top-right-radius: 16rpx;
				  border-top-left-radius: 16rpx;
				  color: #12a15c;
				  background-color: rgba(0,0,0,0.5);
  	  		  }
  	  		  .live-address{
  	  			  white-space: nowrap;
  	  			  overflow: hidden;
  	  			  text-overflow: ellipsis;
				  padding: 0 20rpx;
				  font-size: 24rpx;
  	  		  }
  	  	  }
  	  }
  }
</style>